package com.cheer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheer.dao.ConfigSwitchDao;
import com.cheer.entity.ConfigSwitch;
import com.cheer.enums.SwitchEnum;
import com.cheer.exception.ServiceException;
import com.cheer.service.ConfigSwitchService;
import com.cheer.vo.ConfigSwitchVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service("configSwitchService")
public class ConfigSwitchServiceImpl extends ServiceImpl<ConfigSwitchDao, ConfigSwitch> implements ConfigSwitchService {


    @Autowired
    private ConfigSwitchDao configSwitchDao;


    @Override
    public List<ConfigSwitchVO> info() {

        List<ConfigSwitch> list = list();
        List<ConfigSwitchVO> configSwitchVOS = BeanUtil.copyToList(list, ConfigSwitchVO.class);

        return configSwitchVOS;
    }

    @Override
    public void updateStatus(Long id, Integer status) {

        checkParam(id, status);
        ConfigSwitch configSwitch = new ConfigSwitch();
        configSwitch.setId(id);
        configSwitch.setStatus(status);
        updateById(configSwitch);
    }

    @Override
    public void updateTime(Long id, Date endTime) {

        checkParam(id, endTime);
        if(endTime.after(new Date()) == false){
            throw new ServiceException("截止日期需在当前日期后！");
        }
        ConfigSwitch configSwitch = new ConfigSwitch();
        configSwitch.setId(id);
        configSwitch.setEndTime(endTime);
        updateById(configSwitch);
    }

    @Override
    public ConfigSwitch getSwitchByEnum(SwitchEnum switchEnum) {

        String alias = switchEnum.getAlias();
        ConfigSwitch configSwitch = configSwitchDao.getByAlias(alias);
        return configSwitch;
    }

    private void checkParam(Long id, Object status) {

        if(ObjectUtil.isNull(id) || ObjectUtil.isNull(status)){
            throw new ServiceException("参数异常！");
        }
        List<ConfigSwitchVO> info = info();
        List<Long> ids = info.stream().map(ConfigSwitchVO::getId).collect(Collectors.toList());
        if(ids.contains(id) == false){
            throw new ServiceException("未查询到配置的ID！");
        }
    }



}